package ziam

import (
	apiv1 "gitee.com/youkelike/ziam/zsdk2/gosdk/service/ziam/apiserver/v1"
	authzv1 "gitee.com/youkelike/ziam/zsdk2/gosdk/service/ziam/authz/v1"
	"gitee.com/youkelike/ziam/zsdk2/rest"
)

type ZiamInterface interface {
	APIV1() apiv1.APIV1Interface
	AuthzV1() authzv1.AuthzV1Interface
}

// 因为 apiV1、authzV1 的构造方法会返回错误，所以要先实例化后存到字段，否则要打断链式调用来处理错误，
type ZiamClient struct {
	apiV1   *apiv1.APIV1Client
	authzV1 *authzv1.AuthzV1Client
}

func (c *ZiamClient) APIV1() apiv1.APIV1Interface {
	return c.apiV1
}

func (c *ZiamClient) AuthzV1() authzv1.AuthzV1Interface {
	return c.authzV1
}

func NewForConfig(c *rest.Config) (*ZiamClient, error) {
	// 浅拷贝
	configShallowCopy := *c

	var ic ZiamClient
	var err error

	if (!c.Insecure && c.ServerName == "api.ziam.com") || c.Insecure {
		ic.apiV1, err = apiv1.NewForConfig(&configShallowCopy)
		if err != nil {
			return nil, err
		}
	}

	if (!c.Insecure && c.ServerName == "authz.ziam.com") || c.Insecure {
		ic.authzV1, err = authzv1.NewForConfig(&configShallowCopy)
		if err != nil {
			return nil, err
		}
	}

	return &ic, nil
}

func NewForConfigOrDie(c *rest.Config) *ZiamClient {
	var ic ZiamClient
	ic.apiV1 = apiv1.NewForConfigOrDie(c)
	ic.authzV1 = authzv1.NewForConfigOrDie(c)

	return &ic
}

func New(c rest.Interface) *ZiamClient {
	var ic ZiamClient
	ic.apiV1 = apiv1.New(c)
	ic.authzV1 = authzv1.New(c)

	return &ic
}
